package com.songxh.common;

import com.sun.org.apache.bcel.internal.generic.RET;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.object.UpdatableSqlQuery;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理，就不用在其他地方来单独添加异常
 *
 * @ControllerAdvice(annotations = {RestController.class})
 * 拦截选择包含RestController这个注解的类
 *
 * @ResponseBody 响应返回一个json数据
 * @author songxh
 * @create 2022-04-22-22:13
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理 添加时遇见重复name时的异常
     * @param ex  异常的类型
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg=split[2]+" 用户名已存在";
            return R.error(msg);
        }


        return R.error("未知错误");
    }


    /**
     * 处理自己的异常
     * @param ex  异常的类型
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){

        return R.error(ex.getMessage());
    }

}
